import { useDrag } from 'react-dnd'
import classnames from 'classnames'
import useToggle from '@/hooks/useToggle'
import useFieldIcon from '@/hooks/useFieldIcon'
import IconFont from '@/components/IconFont'
import styles from './index.module.less'

const Item = ({ field, isChild, isCollapse, toggle }) => {
  const [fieldIcon] = useFieldIcon(field)
  return (
    <>
      {isChild ? (
        <IconFont
          className={classnames(styles['field-icon'], 'icon-color-base')}
          type={isCollapse ? 'icon-pull-up' : 'icon-drop-down'}
          onClick={toggle}
        />
      ) : null}
      <IconFont className={styles['field-icon']} type={fieldIcon} />
      <span className="ellipsis">{field.title}</span>
    </>
  )
}

const FieldItem = ({ field }) => {
  const [isCollapse, { toggle }] = useToggle(true)

  const { children } = field
  const isChild = children?.length

  const [{ isDragging }, drag] = useDrag({
    type: field.fieldClassify,
    item: () => field,
    canDrag: () => {
      return !isChild
    },
    collect: (monitor) => ({
      isDragging: monitor.isDragging()
    })
  })

  const item = { field, isChild, isCollapse, toggle }

  return (
    <>
      <div ref={drag} className={styles['fields-item']} style={{ opacity: isDragging ? 0.4 : 1 }}>
        <Item {...item} />
      </div>
      {isChild && isCollapse ? (
        <div className={styles['field-child']}>
          {children.map((child) => (
            <FieldItem key={child.id} field={child} />
          ))}
        </div>
      ) : null}
    </>
  )
}

export default FieldItem
